package com.slkj.controller;

import com.alibaba.fastjson.JSONObject;
import com.slkj.dto.Result;
import com.slkj.dto.StatusCode;
import com.slkj.entity.File;
import com.slkj.mapper.FileMapper;
import com.slkj.util.FileManager;
import com.slkj.util.RequestResponseBox;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName FileController.java
 * @Description TODO
 * @createTime 2020年03月15日 13:55:00
 */
@CrossOrigin
@Transactional
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Autowired
    FileMapper fileMapper;

    private Logger log = LoggerFactory.getLogger(FileController.class);


    @Autowired
    private FileManager fileManager;


    @PostMapping("fileUpload")
    public Result fileUpload(MultipartHttpServletRequest multipartHttpServletRequest) throws Exception {
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        log.info("----------------------->>>fileUpload(@RequestParam(value = \"file\") MultipartFile multipartFile) ");
        File fileupload = fileManager.fileupload(multipartHttpServletRequest, username);
        return new Result(true, StatusCode.OK, "上传成功", fileupload);
    }

    @PostMapping(value = "fileDownload", produces = "charset/utf-8")
    public void fileDownload(@RequestBody String data) throws IOException, MyException {
        log.info("----------------------->>>fileDownload(@RequestBody String data) ");
        JSONObject jsonObject = JSONObject.parseObject(data);
        String fileUrl = jsonObject.getString("fileUrl");
        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        if (StringUtils.isBlank(fileUrl)) {
            throw new RuntimeException("下载失败");
        }

        if (StringUtils.isBlank(fileUrl)) {
            throw new RuntimeException("下载失败");
        }
        List<File> files = fileMapper.selectByfileUrl(fileUrl);
        if (files == null) {
            throw new RuntimeException("下载失败");
        }

        if (files.size() == 0) {
            throw new RuntimeException("下载失败");
        }
//        java.io.File file = new java.io.File();
        fileUrl = fileUrl.substring(fileUrl.indexOf("/"));
        String substr = fileUrl.substring(fileUrl.indexOf("group"));
        String group = substr.split("/")[0];
        String remoteFileName = substr.substring(substr.indexOf("/") + 1);
        String specFileName = files.get(0).getFileName();
        ByteArrayInputStream byteArrayInputStream = fileManager.download(group, remoteFileName, specFileName);
        // 配置文件下载
        RequestResponseBox.getResponse().setHeader("content-type", "application/octet-stream");
        RequestResponseBox.getResponse().setContentType("application/octet-stream");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 下载文件能正常显示中文
        specFileName = specFileName.substring(specFileName.lastIndexOf("."));
        try {
            RequestResponseBox.getResponse().setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(simpleDateFormat.format(new
                    Date()) + specFileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 实现文件下载
        byte[] buffer = new byte[1024];

        try {
            RequestResponseBox.getResponse().setHeader("Content-Length", byteArrayInputStream.available() + "");
            RequestResponseBox.getResponse().setContentType("application/octet-stream");
            OutputStream os = RequestResponseBox.getResponse().getOutputStream();
            int i = byteArrayInputStream.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = byteArrayInputStream.read(buffer);
            }
            log.info("下载成功!" + specFileName);
        } catch (Exception e) {
            log.info("下载失败！！！!");
        } finally {
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    @PostMapping(value = "fileDownload", produces = "charset/utf-8")
//    public void fileDownload(@RequestBody String data) throws IOException, MyException {
//        log.info("----------------------->>>fileDownload(@RequestBody String data) ");
//        JSONObject jsonObject = JSONObject.parseObject(data);
//        String fileUrl = jsonObject.getString("fileUrl");
//        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
//        if (StringUtils.isBlank(fileUrl)) {
//            throw new RuntimeException("下载失败");
//        }
//
//        if (StringUtils.isBlank(fileUrl)) {
//            throw new RuntimeException("下载失败");
//        }
//        List<File> files = fileMapper.selectByfileUrl(fileUrl);
//        if (files == null) {
//            throw new RuntimeException("下载失败");
//        }
//
//        if (files.size() == 0) {
//            throw new RuntimeException("下载失败");
//        }
//
//        fileUrl = fileUrl.substring(fileUrl.indexOf("/"));
//        String substr = fileUrl.substring(fileUrl.indexOf("group"));
//        String group = substr.split("/")[0];
//        String remoteFileName = substr.substring(substr.indexOf("/") + 1);
//        String specFileName = files.get(0).getFileName();
//        ByteArrayInputStream byteArrayInputStream = fileManager.download(group, remoteFileName, specFileName);
//        try {
//            HttpServletResponse response = RequestResponseBox.getResponse();
//            HttpServletRequest request = RequestResponseBox.getRequest();
//            String agent = request.getHeader("User-Agent").toUpperCase();
//            if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {
//                //微软的浏览器(IE和Edge浏览器)
//                specFileName = URLEncoder.encode(specFileName, "UTF-8");
//            } else {
//                specFileName = new String(specFileName.getBytes("UTF-8"), "iso-8859-1");
//            }
//            response.setHeader("Content-Disposition", "filename=" + specFileName);
//            OutputStream out = response.getOutputStream();
//
//            byte[] b = new byte[1024];
//            int length = 0;
//            while ((length = byteArrayInputStream.read(b)) != -1) {
//                out.write(b, 0, length);
//            }
//            byteArrayInputStream.close();
//            out.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}